<?php

/**
 * 科别设置表
 * 
 * @version 1.0
 * @date 2013-12-13
 */

class DefaultController extends FController {

     public function accessRules() {
        $config = array(
            'index' => 1
        );
        return ZRole::auth("disciplin", $config);
    }
 
    public function __common() {
        parent::init();
        if (empty($this->cLoginUser)) {
            $this->redirect($this->createUrl('/site/login'));
        }

        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    /**
	*	@ 列表显示
	*	@ yindebin 
	*	@ 2013-12-13 pm
	*
	*/
    public function actionIndex() {
        $this->__common();
		$conn = Yii::app()->db;
                $this->title='科别信息设置';
		$s['disciplin_code'] = Yii::app()->request->getParam('disciplin_code');
		$s['disciplin_name'] = Yii::app()->request->getParam('disciplin_name');
		$s['disciplin_nick'] = Yii::app()->request->getParam('disciplin_nick');
		$s['is_display'] = Yii::app()->request->getParam('is_display');
		$s['disciplin_type'] = Yii::app()->request->getParam('disciplin_type');
		$s['subject_id'] = Yii::app()->request->getParam('subject_id');
		$s['edu_type'] = Yii::app()->request->getParam('edu_type');
		$s = ZTask::dis_input($s);
		$s = Func::fAddslashes($s);
		$where = ' AND A."is_del" = 0';
		$order = ' ORDER BY A."disciplin_code"';
		$group = '';
		# 条件拼接 #
		
		if(Func::check_search($s['disciplin_code'])){
			$where.= ' AND A."disciplin_code" LIKE '."'%".$s['disciplin_code']."%'";
		}
		if(Func::check_search($s['disciplin_name'])){
			$where.= ' AND A."disciplin_name" LIKE '."'%".$s['disciplin_name']."%'";
		}
		if(!empty($s['disciplin_type'])){
			$where.= ' AND A."disciplin_type" = '."'".$s['disciplin_type']."'";
		}
		if(Func::check_search($s['disciplin_nick'])){
			$where.= ' AND A."disciplin_nick" LIKE '."'%".$s['disciplin_nick']."%'";
		}
		
		if(!empty($s['edu_type'])){
			$ssql = 'SELECT * FROM "{{disciplin_subject}}" WHERE "subject_id" = '.$s['edu_type'];
			$sData = $conn->createcommand($ssql)->queryAll();
			$disciplin_id = "";
			if(!empty($sData)){
				
				foreach ($sData as $sv){
					$disciplin_id .= $sv['disciplin_id'].",";	
				}
				
				$disciplin_id .= 0;
				$where.= ' AND A."disciplin_id" IN ('.$disciplin_id.')';
			}
			$disciplin_id .= 0;
			$where.= ' AND A."disciplin_id" IN ('.$disciplin_id.')';
		}
	
		$select = 'SELECT A.* FROM "{{disciplin}}"  A';
		$sql = " WHERE 1=1 ".$where;
	
        	$selectSql = $select.$sql.$order;
		$countSql = 'SELECT COUNT(*) FROM "{{disciplin}}"  A'.$sql;
		
		$data = ZCommon::getDaoPageList($selectSql, $countSql, 8);
		if(!empty($data['listDatas'])){
			foreach($data['listDatas'] as $k=>$v){
				$result = array();
				
				$swhere = ' AND C."disabled" = 1 AND C."is_del" = 0';
				$sorder = ' ORDER BY C."subject_id" DESC';
				
				$swhere.= ' AND B."disciplin_id" = '."'".$v['disciplin_id']."'";
				$subject = ' SELECT C."subject_id",C."subject_name" FROM "{{disciplin_subject}}" B ';
				$subjectsql = ' LEFT JOIN "{{subject}}" C ON B."subject_id" = C."subject_id" WHERE 1=1 '.$swhere;
				
				$subSelectSql = $subject.$subjectsql.$sorder;
				$result['subject_info'] = $conn->createcommand($subSelectSql)->queryAll();
				$data['listDatas'][$k] = array_merge($data['listDatas'][$k],$result);
			}
		}
	
 
		#  取学科  #
		$subject = array();
		$subject = $this->_getSubjectInfo();
	
		$pageUrl = $this->createUrl('/disciplin/default/index',$s);
        $this->render('index',array(
			'data'	=>$data['listDatas'],
			'pages' => $data['pages'],
			'search'	=> $s,
			'subject'	=> $subject,
			'pageUrl' => $pageUrl
		));
    }

    //更新
    public function actionUpdate() {
		
        //$this->__common();
         $this->title='科别信息设置';
		$conn = Yii::app()->db;
		$this->layout = "//layouts/main_window";    
		
		$disciplin_id = (int)Yii::app()->request->getparam('disciplin_id');
		$disciplin_id = (!empty($_POST['info']['disciplin_id'])) ? $_POST['info']['disciplin_id'] : $disciplin_id;
		
		$model = Disciplin::model()->findByPk($disciplin_id);
		if(empty($model)){
			$this->redirect ( $this->createUrl ( 'index' ) );
			exit;
		}
		
		if(!empty($_POST['submit'])){
			$data = ZTask::dis_input($_POST['info']);
			$data['disabled'] = (!empty($data['disabled'])) ? $data['disabled'] : 0;
			$data['checkbox'] = (!empty($_POST['check'])) ? $_POST['check'] : array();
			#  验证代码  #
			$check = $this->checkDisciplinCode($data['disciplin_code'],$data['disciplin_id']);
			if (!empty($check)){
				$this->frameAjaxMessage(null,'代码已被占用');
				exit;
			}
			#  验证简称  #
			$check_nick = $this->checkDisciplinNick($data['disciplin_nick'],$data['disciplin_id']);
			if (!empty($check_nick)){
				$this->frameAjaxMessage(null,'简称已被占用');
				exit;
			}
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
			$model->attributes = $data;
			if($model->save()){
				$deleted = DisciplinSubject::model()->deleteAll('"disciplin_id" = '."'".$disciplin_id."'");
				foreach($data['checkbox'] as $cv){
						$sql = 'INSERT INTO "{{disciplin_subject}}" VALUES('."'".$disciplin_id."'".','."'".$cv."'".')';
						$result = $conn->createcommand($sql)->execute();
					}
				$this->frameAjaxMessage('index','简称已被占用');
			}else{
				$this->frameAjaxMessage('index','简称已被占用');
			}
		}else{
			#  取关联的科目  #
			$dsModel = DisciplinSubject::model()->findAll('"disciplin_id" = '."'".$disciplin_id."'");
			$dsData = array();
			if(!empty($dsModel)){
				foreach($dsModel as $dv){
					$checkbox = $dv->attributes;
					$dsData[] = $checkbox['subject_id'];
				}
			}
			#  取出所有使用的科目  #
			$subject = array();
			$subject = $this->_getSubjectInfo();
			
			$this->render('update',array(
				'data'	=> $model->attributes,
				'subject'	=> $subject,
				'checkbox'	=> $dsData
			));
		}
        
    }

    //添加
    public function actionAdd() {
       // $this->__common();
		$conn = Yii::app()->db;
		 $this->title='科别信息设置';
		$this->layout = "//layouts/main_window";    
		
       if(!empty($_POST['submit'])){
			$data = ZTask::dis_input($_POST['info']);

			$data['disabled'] = (!empty($data['disabled'])) ? $data['disabled'] : 0 ;
			$data['disciplin_type'] = (!empty($data['disciplin_type']))?$data['disciplin_type']:0;
			$data['checkbox'] = (!empty($_POST['check'])) ? $_POST['check'] : array();
			$data['disciplin_code'] = strtolower($data['disciplin_code']);
			# 验证代码  #
			$check = $this->checkDisciplinCode($data['disciplin_code']);
			if (!empty($check)){
				$this->frameAjaxMessage(null,'代码已被占用');
				exit;
			}
			# 验证简称  #
			$check_nick = $this->checkDisciplinNick($data['disciplin_nick']);
			if(!empty($check_nick)){
				
				$this->frameAjaxMessage(null,'简称已被占用');
				exit;
			}
			
			$data['create_user'] = $this->cLoginUser['cuser']['id'];
           	$data['create_time'] = time();
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
               
			$model = new Disciplin();
			$model->attributes = $data;
			if($model->save()){
				$id = $model->attributes['disciplin_id'];
				if(!empty($data['checkbox'] )){
					
					foreach($data['checkbox'] as $cv){
						$sql = 'INSERT INTO "{{disciplin_subject}}" VALUES('."'".$id."'".','."'".$cv."'".')';
						$result = $conn->createcommand($sql)->execute();
					}
				}
				$this->frameAjaxMessage("index");
			}else{
				$this->frameAjaxMessage(null,'添加失败');
			}
		}else{
			#  取出所有使用的科目  #
			$subject = array();
			$subject = $this->_getSubjectInfo();

			$this->render('add',array(
				'subject'	=> $subject
			));
		}
    }

    //删除
    public function actionDelete() {
        $disciplin_id = (int)Yii::app()->request->getparam('disciplin_id');

		if(!empty($disciplin_id)){
			$model = Disciplin::model()->findByPk($disciplin_id);
			if(empty($model)){
				$this->frameAjaxMessage('index','没有要删除的数据');
				exit;
			}
			$dsModel = new DisciplinSubject;
			$sql = 'UPDATE "{{disciplin}}" SET "is_del" = 1 WHERE "disciplin_id" = '.$disciplin_id;
			$query = Yii::app()->db->createCommand($sql)->execute();
			if ($query) {
				$this->frameAjaxMessage('index');
				exit;
			} else {
				$this->frameAjaxMessage('index','删除失败');
				exit;
			}
		}else{
			$this->frameAjaxMessage('index','参数错误!');
		}
    }
    
	/**
	* @ 批量删除学段
	* @ yindebin
	* @ 2014-01-06 pm
	*
	*/
	public function actionDelete_all(){
		$disciplin_id = Yii::app ()->request->getparam ( 'disciplin_id' );
		if (! empty ( $disciplin_id )) {
			$delete = 'UPDATE "{{disciplin}}" SET "is_del" = 1 WHERE "disciplin_id" IN ('.$disciplin_id.')';
			$query = Yii::app()->db->createCommand($delete)->execute();
			echo 1;
		}else{
			echo 2;
		}
	}
	/**
	*	@ 获取学科信息
	*	@ yindebin 
	*	@ 2013-12-13 pm
	*
	*/
	public function _getSubjectInfo(){
		#  取出所有使用的学科  #
		$eduModel = Subject::model()->findAll('"disabled" = 1 AND "is_del" = 0 ORDER BY "subject_id" DESC ');
		$subject = array();
		
		if(!empty($eduModel)){
			foreach($eduModel as $ev){
				$subject[] = $ev->attributes;
			}
		}
		return $subject;
	}

	/**
	 * @ 判断科别代码是否存在
	 * @ yindebin
	 * @ 2013-12-28
	 */
	protected function checkDisciplinCode($disciplin_code,$disciplin_id=''){
		if(empty($disciplin_code))
			return null;
		
		$where = ' AND "disciplin_code" = \''.$disciplin_code.'\' AND "is_del" = 0 ';
		if (!empty($disciplin_id)) {
			$where.= ' AND "disciplin_id" != '."'".$disciplin_id."'";
		}
		$sql = 'SELECT "disciplin_id" FROM "{{disciplin}}" WHERE 1=1 '.$where;
		
		return $result = Yii::app()->db->createCommand($sql)->queryRow();
	}
	
	/**
	 * @ 判断科别代码是否为空
	 * @ yindebin
	 * @ 2013-12-28
	 */
	protected function checkDisciplinNick($disciplin_nick,$disciplin_id=''){
		if(empty($disciplin_nick))
			return null;
		
		$where = ' AND "disciplin_nick" = \''.$disciplin_nick.'\' AND "is_del" = 0 ';
		if (!empty($disciplin_id)) {
			$where.= ' AND "disciplin_id" != '."'".$disciplin_id."'";
		}
		$sql = 'SELECT "disciplin_id" FROM "{{disciplin}}" WHERE 1=1 '.$where;
		
		return $result = Yii::app()->db->createCommand($sql)->queryRow();
	}
	
}